﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace Utils.Extensions
{
	public static class StringExtension
	{
		public static int NthIndexOf(this string target, string value, int n)
		{
			if (n <= 0)
				throw new ArgumentOutOfRangeException("n", n, "The n repetition has to be a value greater than 0");

			Match m = Regex.Match(target, "(?s)((" + Regex.Escape(value) + ").*?){" + n + "}");

			if (m.Success)
				return m.Groups[2].Captures[n - 1].Index;
			else
				return -1;
		}

		public static string Crypt(this string text)
		{
			return !string.IsNullOrEmpty(text) ? Convert.ToBase64String(ProtectedData.Protect(Encoding.Unicode.GetBytes(text), new byte[] { 1, 2, 3 }, DataProtectionScope.LocalMachine)) : text;
		}

		public static string Decrypt(this string text)
		{
			return !string.IsNullOrEmpty(text) ? Encoding.Unicode.GetString(ProtectedData.Unprotect(Convert.FromBase64String(text), new byte[] { 1, 2, 3 }, DataProtectionScope.LocalMachine)) : text;
		}
	}
}